﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;

using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Test;
using PdfLib;

namespace PdfLib.Test.Searcher
{
    [ManualTestCase("Pattern searcher", "Searcher")]
    public partial class TestCase_PatternSearcher : UserControl
    {
        public TestCase_PatternSearcher()
        {
            InitializeComponent();
        }

        private void btn_Open_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "PDF files(*.pdf)|*.pdf|All files(*.*)|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                this.txt_PdfPath.Text = dlg.FileName;
                int pageCount = PdfPropertyReader.GetPageCount(this.txt_PdfPath.Text);
                this.num_Page.Value = 1;
                this.num_Page.Maximum = pageCount;

                this.OpenPage(this.txt_PdfPath.Text, (int)this.num_Page.Value);
            }
        }

        private void btn_Open2_Click(object sender, EventArgs e)
        {
            this.OpenPage(this.txt_PdfPath.Text, (int)this.num_Page.Value);
        }

        private void OpenPage(string pdfFilePath, int pageNum)
        {
            this.pic_PatternPositions.Image = null;

            
            try
            {
                Image pageImg = PdfTextReader.GetPageTextLayout(pdfFilePath, pageNum);
                this.pic_PDF.Image = pageImg;
                Dictionary<RectangleF, double> rectsFound =
                    PdfPatternSearcher.FoundPatterns(
                        pdfFilePath, pageNum,
                        this.txt_Pattern.Text, this.ck_Regex.Checked, 0.9);

                Image img = PdfTextReader.GetPageTextLayout(pdfFilePath, pageNum);
                Graphics g = Graphics.FromImage(img);
                if(rectsFound !=null && rectsFound.Count>0)
                {
                    Color highlighter = Color.FromArgb(125, Color.Red);
                    foreach(RectangleF rect in rectsFound.Keys)
                    {
                        g.DrawRectangle(new Pen(highlighter, 1),
                                        (int) rect.X,
                                        (int) rect.Y,
                                        (int) rect.Width,
                                        (int) rect.Height);
                    }
                }

                this.pic_PatternPositions.Image = img;
                g.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
